﻿package common.transaction;

import java.sql.Connection;

import util.DebugUtil;

import common.proxy.ConnectionProxy;


public class JdbcTransactionController implements ITransactionController {
	
	private ConnectionProxy obj;
	private boolean isNest = false;//是否嵌套事务

	public JdbcTransactionController(ConnectionProxy obj) {
		this.obj = obj;
	}

	public void setNestTransaction(boolean isNest) {
		this.isNest = isNest;
	}

	public Object getProxyObj() {
		return obj.getProxyObj();
	}
	
	/**
	 * 加入一个事务对象,进行管理
	 */
	public void addTransaction(IServiceTransaction busObj) {
		busObj.setProxyObj(obj.getProxyObj());//设置连接为代理类
		busObj.setNestTransaction(true);//设置为嵌套事务
		DebugUtil.print(this.getClass().getName() + "设置事务嵌套:" + busObj.getNestTransaction());
	}
	
	/**
	 * 事务开始
	 */
	public Object begin() {
		DebugUtil.print(this.getClass().getName() + ":begin");
		try {
			if (this.isNest || this.obj.getProxyObj() == null) {
				return null;
			}
			this.obj.setAutoCommitFlag(false);//在调用commit方法的时候才设置为true
			this.obj.setCloseFlag(false);//在调用end方法的时候才设置为true
			
			Connection conn = ((Connection)obj.getProxyObj());
			conn.setAutoCommit(false);//设置不自动提交才能回滚
			DebugUtil.print(this.getClass().getName() + ":setAutoCommit设置为false");
			return null;

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 事务提交
	 */
	public void commit(Object trans) {
		DebugUtil.print(this.getClass().getName() + ":commit");
		try {
			if (this.isNest || this.obj.getProxyObj() == null) {
				return;
			}
			obj.setAutoCommitFlag(true);
			Connection conn = ((Connection)obj.getProxyObj());
			conn.commit();
		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	/**
	 * 事务回滚
	 */
	public void rollback(Object trans) {
		DebugUtil.print(this.getClass().getName() + ":rollback");
		try {
			if (this.obj.getProxyObj() == null) {
				return;
			}
			Connection conn = ((Connection)obj.getProxyObj());
			conn.rollback();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 事务结束
	 */
	public void end() {
		DebugUtil.print(this.getClass().getName() + ":end");
		try {
			// 容错处理
			if (this.isNest || this.obj.getProxyObj() == null) {
				return;
			}

			this.obj.setCloseFlag(true);//设置为true才能关闭
			((Connection)obj.getProxyObj()).close();
			
			TransactionControllerFactory.clear(); // 释放资源
		} catch (Exception e) {
			e.printStackTrace();
		}
		DebugUtil.print(this.getClass().getName() + ":已经关闭");
	}

}